<template>
    <div class="goods-detail">
        <a-modal width="1300px" :visible="visible" title="编辑资源" @cancel="closeModal" class="yuan-modal goods-detail-modal"
            :dialog-style="{ top: '20px' }">
            <a-spin tip="Loading..." :spinning="saveLoading">
                <a-form-model layout="inline" class="yuan-form" ref="form" :model="formData" :rules="rules"
                    :class="isShow?'disable-form':''" :label-col="{ style: { width: '150px' } }"
                    :wrapper-col="{ style: { width: 'calc(100% - 160px)' } }">

                    <div class="form-panel yuan-form-col3">
                        <div class="form-panel-box">
                            <div class="form-title">商品信息</div>
                            <a-form-model-item class="yuan-form-item" label="商品分类" prop="twoClassifyId">
                                <a-cascader class="yuan-form-input" v-model="formData.classifyId" :options="categoryData"
                                    placeholder="请选择商品分类" @change="onCategoryChange" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="品牌" prop="brand">
                                <a-input class="yuan-form-input" placeholder="商品品牌" v-model="formData.brand"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="商品名称" prop="name">
                                <a-input class="yuan-form-input" placeholder="最多可输入100个字符" v-model="formData.name"></a-input>
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="产地" prop="placeOfOrigin">
                                <a-cascader class="yuan-form-input" :options="addrData" v-model="formData.placeData"
                                    placeholder="请选择" @change="onAddrChange" />
                            </a-form-model-item>
                            <a-form-model-item class="yuan-form-item" label="关键词" prop="keyword">
                                <a-input class="yuan-form-input" placeholder="以逗号分隔，最多5个" v-model="formData.keyword"></a-input>
                            </a-form-model-item>
                            <!-- <a-form-model-item class="yuan-form-item" label="是否允许使用优惠券" prop="ifUsePreferentialCard">
                                <a-radio-group class="yuan-form-input" v-model="formData.ifUsePreferentialCard">
                                    <a-radio value="1">是</a-radio>
                                    <a-radio value="0">否</a-radio>
                                </a-radio-group>
                            </a-form-model-item> -->
                            <!-- <a-form-model-item class="yuan-form-item" label="商品运费(元)" prop="freightYuan">
                                <a-input class="yuan-form-input" type="number" placeholder="固定运费"
                                    v-model="formData.freightYuan"></a-input>
                            </a-form-model-item> -->
                            <!-- <a-form-model-item class="yuan-form-row" label="商品描述" prop="description">
                                <a-input type="textarea" style="width: 500px;background-color:#F7F7F7" :rows="5"
                                    v-model="formData.description" placeholder="请输入商品描述" :maxLength="500" />
                            </a-form-model-item> -->

                            <a-form-model-item label="商品图片" class="yuan-form-row" v-if="pageReady" prop="mustTips">
                                <UploadVue :uploadLength="6" @uploadChange="uploadChangeCoverImageUrl"
                                    :defImgList="formData.pictures.length>0?formData.pictures:[]" />
                                <div style="line-height:30px">jpg.png.gif格式.不超过2MB，最多6张</div>
                            </a-form-model-item>

                            <a-form-model-item class="yuan-form-row" label="商品详情" prop="details">
                                <div class="editor" style="min-height:300px;width:1000px">
                                    <Toolbar style="border-bottom: 1px solid #ccc;" :editor="editorRef"
                                        :defaultConfig="editorConfig.toolbarConfig" mode="default" />
                                    <Editor v-model="formData.details" :defaultConfig="editorConfig" mode="default"
                                        @onCreated="handleCreated" />
                                </div>
                            </a-form-model-item>
                        </div>

                        <div class="form-panel-box" style="margin-top:20px">
                            <div class="form-title">
                                <span style="flex-grow:1">商品规格</span>
                                <a-button class="case-btn" type="primary" @click="addSize">新增</a-button>
                            </div>
                            <div class="case-list" v-for="(item,index) in sizeList">
                                <div class="case-title">
                                    规格{{index+1}}
                                    <a-button class="case-btn" type="danger" @click="delSize(index)"
                                        v-if="sizeList.length>=2">删除</a-button>
                                </div>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="名称" prop="mustTips">
                                    <a-input class="yuan-form-input" v-model="item.name" placeholder="请输入规格名称"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="价格" prop="mustTips">
                                    <a-input class="yuan-form-input" v-model="item.priceYuan" placeholder="请输入价格"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-item yuan-form-col3" label="商品库存" prop="mustTips">
                                    <a-input class="yuan-form-input" v-model="item.inventory" placeholder="请输入商品库存"></a-input>
                                </a-form-model-item>
                                <a-form-model-item class="yuan-form-row" label="库存预警值" prop="mustTips">
                                    <a-input class="yuan-form-input" v-model="item.inventoryWarn" placeholder="请输入商品库存"></a-input>
                                    <div style="line-height:30px">当库存低于预警值时系统会进行提醒，且商品列表页库存列红字提醒，0为不预警</div>
                                </a-form-model-item>
                                <div class="case-btn-box">

                                </div>
                            </div>
                        </div>
                    </div>
                </a-form-model>
            </a-spin>
            <template slot="footer">
                <template v-if="isShow">
                    <a-button @click="closeModal">
                        关闭
                    </a-button>
                </template>
                <template v-else>
                    <a-button @click="modalOk" type="primary" :loading="saveLoading">
                        确认保存
                    </a-button>
                    <a-button @click="closeModal">
                        取消
                    </a-button>
                </template>

            </template>
        </a-modal>
    </div>
</template>

<script lang="ts">
import { Component, Prop, Watch, Vue } from "vue-property-decorator";
import UploadVue from "@/components/upload.vue";
import api from "@/api/api";
import areaJson, { getAreaWords } from "@/utils/area";
import { MENU_CONF, toolbarConfig } from "@/utils/wangeditors";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import shopMallApi from "@/api/shopMallApi";
import { format } from "@/utils";
@Component({
    name: "tpl",
    components: { UploadVue, Editor, Toolbar },
})
export default class extends Vue {
    @Prop({ default: false }) visible!: boolean;
    @Prop({ default: false }) isShow!: boolean;
    @Prop({ default: "" }) editInfo!: any;

    @Watch("visible")
    visibleChange() {
        if (this.visible) {
            if (this.editInfo.id) {
                this.getGoodsDetail();
            } else {
                this.formData = {
                    pictures: [],
                    twoClassifyId: undefined,
                    status: 0,
                    ifSubmitAudit: 0,
                };
                this.sizeList = [{}];
                this.pageReady = true;
            }
        } else {
            this.pageReady = false;
        }
    }
    categoryData: any[] = [];
    saveLoading = false;
    formData: any = {
        pictures: [],
        twoClassifyId: undefined,
    };
    mustNullTips(rule, value, callback) {
        callback();
    }
    rules = {
        twoClassifyId: [{ required: true, message: "请选择商品分类", trigger: "change" }],
        freightYuan: [{ required: true, message: "请填写商品运费", trigger: "change" }],
        brand: [{ required: true, message: "请填写商品品牌", trigger: "change" }],
        name: [{ required: true, message: "请填写商品名称", trigger: "change" }],
        placeOfOrigin: [{ required: true, message: "请选择商品产地", trigger: "change" }],
        keyword: [{ required: true, message: "请填写关键词", trigger: "change" }],
        ifUsePreferentialCard: [{ required: true, message: "请选择是否使用优惠券", trigger: "change" }],
        // description: [{ required: true, message: "请填写商品描述", trigger: "change" }],
        details: [{ required: true, message: "请填写商品详情", trigger: "change" }],
        mustTips: [{ required: true, message: "请选择时间", trigger: "change", validator: this.mustNullTips }],
    };
    pageReady = false;

    async mounted() {
        this.getClassifyData();
        this.setAddrData();
    }
    closeModal() {
        (this.$refs.form as any).resetFields();
        this.$emit("closeModal");
    }

    async modalOk() {
        if (this.formData.pictures.length === 0) {
            this.$message.error("请上传商品封面图");
            return;
        }
        let sizeTips = "";
        this.sizeList.forEach((item) => {
            if (!item.priceYuan || !item.inventory || !item.name) {
                sizeTips = "请完善商品规格的价格和库存信息";
            }
        });

        if (sizeTips) {
            this.$message.error(sizeTips);
            return;
        }

        (this.$refs.form as any).validate(async (valid: boolean) => {
            if (!valid) {
                this.$message.error("必填信息不完整，请检查后重试");
                return;
            }
            this.saveLoading = true;
            try {
                const data = {
                    ...this.formData,
                    freight: Number(this.formData.freightYuan) * 100 || 0,
                    specificationJson: this.sizeList.map((item, idx) => {
                        return {
                            id: item.id || format(new Date(), "yyyyMMddhhmmss_" + idx),
                            price: Number(item.priceYuan) * 100,
                            name:item.name,
                            inventory: Number(item.inventory),
                            inventoryWarn: Number(item.inventoryWarn) || 0,
                        };
                    }),
                    pictureJson: this.formData.pictures.map((item,idx) => {
                        let ifMasterMap=0
                        if(idx===0) ifMasterMap=1
                        return {
                            url: item,
                            ifMasterMap,
                        };
                    }),
                };
                const res = await shopMallApi.addGoods(data);
                this.$message.success("保存成功");
                this.closeModal();
                this.$emit("resetList");
            } finally {
                this.saveLoading = false;
            }
        });
    }
    uploadChangeCoverImageUrl(e) {
        this.formData.pictures = e.length ? e.map((item) => item.url) : [];
    }
    onCategoryChange(e: any) {
        this.formData.firstClassifyId = e[0];
        this.formData.twoClassifyId = e[1];
    }
    addrData: any[] = [];
    setAddrData() {
        this.addrData = areaJson;
    }
    onAddrChange(e: any) {
        const data = getAreaWords(e);
        this.formData.placeOfOrigin = data.province + data.city + data.district;
        this.formData.placeOfOriginId = data.provinceCode + "," + data.cityCode + "," + data.districtCode;
    }

    editorRef = null;
    editorConfig = {
        placeholder: "请输入内容...",
        //配置工具栏
        toolbarConfig: toolbarConfig,
        MENU_CONF: MENU_CONF,
    };
    handleCreated(editor) {
        this.editorRef = editor; // 记录 editor 实例
    }

    sizeList: any[] = [{}];
    addSize() {
        this.sizeList.push({});
    }
    delSize(index: number) {
        this.sizeList.splice(index, 1);
    }
    async getClassifyData() {
        if (this.categoryData.length > 0) return;
        this.saveLoading = true;
        try {
            const res = await shopMallApi.getClassifyList({});
            const rows = res.data?.rows || [];
            const data = {};
            rows.forEach((item) => {
                if (item.level === "一级") {
                    if (data[item.id]) {
                        data[item.id].label = item.name;
                    } else {
                        data[item.id] = {
                            value: item.id,
                            label: item.name,
                            children: [],
                        };
                    }
                } else {
                    if (data[item.parentId]) {
                        data[item.parentId].children.push({ value: item.id, label: item.name });
                    } else {
                        data[item.parentId] = {
                            value: item.parentId,
                            label: "",
                            children: [{ value: item.id, label: item.name }],
                        };
                    }
                }
            });
            const dataArr: any[] = [];
            for (let i in data) {
                dataArr.push(data[i]);
            }
            this.categoryData = dataArr;
        } finally {
            this.saveLoading = false;
        }
    }

    async getGoodsDetail() {
        this.saveLoading = true;
        try {
            const res = await shopMallApi.getGoodsList({ id: this.editInfo.id });
            const pictures = res.data.pictureJson ? res.data.pictureJson.map((item) => item.url) : [];
            console.info(res.data.pictureJson,pictures)
            // 编辑需要重置所有的状态
            this.formData = {
                ...res.data,
                status: 0,
                ifSubmitAudit: 0,
                auditStatus:0,
                pictures,
                ifUsePreferentialCard: res.data.ifUsePreferentialCard + "",
                freightYuan: Number(res.data.freight) / 100,
                classifyId: [res.data.firstClassifyId, res.data.twoClassifyId],
                placeData: res.data.placeOfOriginId.split(","),
            };
            this.sizeList = res.data.specificationJson
                ? res.data.specificationJson.map((item) => {
                      return {
                          ...item,
                          priceYuan: Number(item.price) / 100,
                      };
                  })
                : [];

            this.pageReady = true;
        } finally {
            this.saveLoading = false;
        }
    }
}
</script>
<style lang="scss">
.goods-detail-modal {
    .case-list {
        background-color: #f7f7f7;
        padding: 10px 15px;
        border-radius: 6px;
        margin-bottom: 10px;
    }
    .case-title {
        font-weight: bold;
        font-size: 15px;
        color: #102040;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
}
</style>
